09. Exercise: Friends
Friends
In C++, friend
classes provide an alternative inheritance mechanism to derived classes. The main difference between classical inheritance and friend inheritance is that a friend
class can access private members of the base class, which isn't the case for classical inheritance. In classical inheritance, a derived class can only access public and protected members of the base class.
Instructions
In this exercise you will experiment with friend classes. In the notebook below, implement the following steps:
- Declare a class
Rectangle
. - Define a class
Square
. - Add class
Rectangle
as a friend of the classSquare
. - Add a private attribute
side
to classSquare
. - Create a public constructor in class
Square
that initializes theside
attribute. - Add private members
width
andheight
to classRectangle
. - Add a
Rectangle()
constructor that takes aSquare
as an argument. - Add an
Area()
function toclass Rectangle
.
Workspace
This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity, so you may be able to download them there.
Workspace Information:
- Default file path:
- Workspace type: jupyter
- Opened files (when workspace is loaded): n/a